package com.tdu.spider.web.controller.same;

import com.tdu.spider.biz.service.same.SameApiService;
import com.tdu.spider.biz.service.same.SameChannelService;
import com.tdu.spider.biz.service.same.vo.*;
import com.tdu.spider.biz.vo.Result;
import com.tdu.spider.model.SameChannelDO;
import com.tdu.spider.web.controller.vo.WebResult;
import org.apache.commons.io.IOUtils;
import org.apache.http.util.Args;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/same")
public class SameApiController {

    private static final Logger LOGGER = LoggerFactory.getLogger(SameApiController.class);
    @Autowired
    private SameApiService     sameApiService;
    @Autowired
    private SameChannelService sameChannelService;


    @RequestMapping("users")
    @ResponseBody
    public Result<List<UserVO>> users() {
        try {
            return WebResult.success(sameApiService.users());
        } catch (Exception e) {
            LOGGER.error("users", e);
            return WebResult.failed("notFound");
        }
    }

    @RequestMapping("senseDetail")
    @ResponseBody
    public Result<SenSeVO> senseDetail(Long senseId) {
        try {
            UserInfoQuery query = new UserInfoQuery();
            query.setSenseId(senseId);
            SenSeVO senSeVO = sameApiService.querySenseDetail(query);
            if (senSeVO != null) {
                return WebResult.success(senSeVO);
            }
        } catch (Exception e) {
            LOGGER.error("senseDetail", e);
        }
        return WebResult.failed("notFound");
    }

    @RequestMapping("userSense")
    @ResponseBody
    @CrossOrigin
    public Result<PageSenseVO> userSense(Long userId, Long offset) {
        try {
            UserInfoQuery query = new UserInfoQuery();
            query.setUserId(userId);
            query.setOffset(offset);
            PageSenseVO pageSenseVO = sameApiService.pageQueryUserSense(query);
            if (pageSenseVO != null) {
                return WebResult.success(pageSenseVO);
            }
        } catch (Exception e) {
            LOGGER.error("userSense", e);
        }
        return WebResult.failed("notFound");
    }

    @RequestMapping("query_user_info")
    @ResponseBody
    public Result<UserVO> queryUserInfo(Long userId) {
        try {
            return WebResult.success(sameApiService.queryUserDetail(userId));
        } catch (Exception e) {
            LOGGER.error("queryUserInfo", e);
            return WebResult.failed("发送失败");
        }
    }

    @RequestMapping("send_msg")
    @ResponseBody
    public Result<SendMessageVO> send_msg(SendMessageVO.MessageBody messageVO) {
        try {
            SendMessageVO sendMessageVO=new SendMessageVO();
            sendMessageVO.setBody(messageVO);
            return WebResult.success(sameApiService.sendPmsg(sendMessageVO));
        } catch (Exception e) {
            LOGGER.error("send_msg", e);
            return WebResult.failed("发送失败");
        }
    }

    @RequestMapping("chart_history")
    @ResponseBody
    public Result<List<UserChatHistoryVO>> chart_history(UserChatHistoryQueryVO query) {
        try {
            List<UserChatHistoryVO> historyVOS = sameApiService.privateHistory(query);
            Collections.reverse(historyVOS);
            return WebResult.success(historyVOS);
        } catch (Exception e) {
            LOGGER.error("chart_history", e);
            return WebResult.failed("查询失败");
        }
    }

    @RequestMapping("query_message")
    @ResponseBody
    public Result<UserMessageResultVO> queryMessage(UserInfoQuery query) {
        try {
            return WebResult.success(sameApiService.queryMessage(query));
        } catch (Exception e) {
            LOGGER.error("queryMessage", e);
            return WebResult.failed("查询失败");
        }
    }

    @RequestMapping("user_channels")
    @ResponseBody
    public Result<List<SameChannelDO>> queryUserChannels(UserInfoQuery query) {
        Args.notNull(query.getUserId(), "userId");
        try {
            List<SameChannelDO> channels = sameApiService.channels(query);
            if (!CollectionUtils.isEmpty(channels)) {
                for (SameChannelDO channel : channels) {
                    query.setChannelId(channel.getId());
                    SameChannelDO detailVO = sameApiService.queryChannelDetail(query);
                    if (detailVO != null && detailVO.getConfig() != null) {
                        channel.setConfig(detailVO.getConfig());
                    }
                }
            }
            return WebResult.success(channels);
        } catch (Exception e) {
            LOGGER.error("queryUserChannels", e);
            return WebResult.failed(e.getMessage());
        }
    }

    @RequestMapping("search_channel")
    @ResponseBody
    public Result<List<SameChannelDO>> search_channel() {
        try {
            List<SameChannelDO> channels = sameChannelService.getAll();
            return WebResult.success(channels);
        } catch (Exception e) {
            LOGGER.error("search_channel", e);
            return WebResult.failed(e.getMessage());
        }
    }


    @RequestMapping("all_channels")
    @ResponseBody
    public Result<List<SameChannelDO>> all_channels() {
        try {
            List<SameChannelDO> channels = sameChannelService.getAll();
            return WebResult.success(channels);
        } catch (Exception e) {
            LOGGER.error("all_channels", e);
            return WebResult.failed(e.getMessage());
        }
    }

    @RequestMapping("find_channels")
    @ResponseBody
    public Result<List<SameChannelDO>> find_channels(String txt) {
        try {
            List<SameChannelDO> channels = sameApiService.querySearchChannel(txt);
            return WebResult.success(channels);
        } catch (Exception e) {
            LOGGER.error("all_channels", e);
            return WebResult.failed(e.getMessage());
        }
    }

    @RequestMapping("query_hot_channel")
    @ResponseBody
    public Result<List<SameChannelDO>> query_hot_channel() {
        try {
            List<SameChannelDO> channels = sameApiService.queryHotChannel();
            return WebResult.success(channels);
        } catch (Exception e) {
            LOGGER.error("query_hot_channel", e);
            return WebResult.failed(e.getMessage());
        }
    }

    @RequestMapping("save_channel")
    @ResponseBody
    public Result<SameChannelDO> save_channel(Long channelId) {
        try {
            SameChannelDO sameChannelDO = sameChannelService.saveChannel(channelId);
            return WebResult.success(sameChannelDO);
        } catch (Exception e) {
            LOGGER.error("save_channel", e);
            return WebResult.failed(e.getMessage());
        }
    }


    @RequestMapping("query_senses")
    @ResponseBody
    public Result<PageSenseVO> querySenseByChannel(UserInfoQuery query) {
        try {
            Args.notNull(query.getChannelId(), "channelId");
            return WebResult.success(sameApiService.pageQueryActivitySense(query));
        } catch (Exception e) {
            LOGGER.error("querySenseByChannel,params:{}", query, e);
            return WebResult.failed(e.getMessage());
        }
    }

    @RequestMapping("like_sense")
    @ResponseBody
    public Result<Boolean> likeSense(UserInfoQuery query) {
        try {
            Args.notNull(query.getSenseId(), "senseId");
            Args.notNull(query.getChannelId(), "channelId");
            return WebResult.success(sameApiService.likeSense(query));
        } catch (Exception e) {
            LOGGER.error("likeSense", e);
            return WebResult.failed(e.getMessage());
        }
    }

    @RequestMapping("batch_like_sense")
    @ResponseBody
    public Result<Boolean> batchLikeSense(List<UserInfoQuery> querys) {
        try {
            Args.notNull(querys, "querys");
            Args.check(querys.size() > 50, "批量点赞接口50/次");
            return WebResult.success(sameApiService.likeSense(querys));
        } catch (Exception e) {
            LOGGER.error("likeSense", e);
            return WebResult.failed(e.getMessage());
        }
    }


    @RequestMapping("create_sense")
    @ResponseBody
    public Result<SenSeVO> createSense(@RequestBody AddSenSeVO addSenSeVO) {
        try {
            Args.notNull(addSenSeVO.getChannelId(), "channelId");
            Args.notNull(addSenSeVO.getText(), "text");
            Args.notNull(addSenSeVO.getUserId(), "userId");
            //是否有文件上传功能
            if (StringUtils.hasLength(addSenSeVO.getFileUrl())) {
                UploadFileVO uploadFileVO = new UploadFileVO();
                uploadFileVO.setFileName(FILE_PATH + addSenSeVO.getFileUrl());
                //获取 token
                UploadTokenResult uploadTokenByUserId = sameApiService.getUploadTokenByUserId(addSenSeVO.getUserId());
                if (uploadTokenByUserId == null) {
                    return WebResult.failed("获取上传Token失败");
                }
                uploadFileVO.setToken(uploadTokenByUserId.getToken());
                LOGGER.info("use token:{},params:{}", uploadTokenByUserId.getToken(), addSenSeVO);
                UploadFileResult uploadFileResult = sameApiService.uploadFile(uploadFileVO);
                if (uploadFileResult != null) {
                    addSenSeVO.setFileUrl(uploadFileResult.getKey());
                } else {
                    LOGGER.warn("uploadFaild error params:{}", uploadFileVO);
                }
            }
            return WebResult.success(sameApiService.createSense(addSenSeVO));
        } catch (Exception e) {
            LOGGER.error("createSense", e);
            return WebResult.failed(e.getMessage());
        }
    }

    public static final String FILE_PATH = "/Users/tangdu/git/tangdu/feature/spider/spider-deploy/tmp/";

    @RequestMapping("uploadFile")
    @ResponseBody
    public Result<String> uploadFile(@RequestParam("file") MultipartFile multipartFile) {
        try {
            if (multipartFile.isEmpty()) {
                return WebResult.failed("文件不能为空!");
            }
            File file = new File(FILE_PATH + File.separator + UUID.randomUUID().toString() + ".jpg");
            OutputStream outputStream = new FileOutputStream(file);
            IOUtils.copy(multipartFile.getInputStream(), outputStream);
            outputStream.close();
            return WebResult.success(file.getName());
        } catch (Exception e) {
            LOGGER.error("uploadFile", e);
            return WebResult.failed(e.getMessage());
        }
    }

    @RequestMapping("delete_sense")
    @ResponseBody
    public Result<Boolean> deleteSenseById(Long senseId) {
        try {
            Args.notNull(senseId, "senseId");
            return WebResult.success(sameApiService.destorySense(senseId));
        } catch (Exception e) {
            LOGGER.error("querySenseByChannel", e);
            return WebResult.failed(e.getMessage());
        }
    }
}
